package com.iqilu.ksd.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.andview.refreshview.XRefreshView;
import com.andview.refreshview.XRefreshViewFooter;
import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.reflect.TypeToken;
import com.iqilu.ksd.MyApplication;
import com.iqilu.ksd.R;
import com.iqilu.ksd.adapter.RadioDetailAdapter;
import com.iqilu.ksd.bean.RadioBean;
import com.iqilu.ksd.bean.UserBean;
import com.iqilu.ksd.constant.Api;
import com.iqilu.ksd.constant.Config;
import com.iqilu.ksd.utils.JSONUtils;
import com.iqilu.ksd.utils.ShareUtils;
import com.iqilu.ksd.view.RadioPlayerView;
import com.iqilu.ksd.widget.LigDialog;
import com.jaeger.library.StatusBarUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.ShareSDK;
import okhttp3.Call;
import okhttp3.Request;

/**
 * Created by Coofee on 2016/11/8.
 */

public class RadioDetailActivity extends BaseActivity implements View.OnClickListener{

    private UserBean user;
    private int catId;
    private int page;
    private RadioBean data;
    private ArrayList<RadioBean> list;
    private boolean firstLoad = true;
    private RadioDetailAdapter adapter;
    private LigDialog ligDialog;

    private ImageView imgBg;
    private RadioPlayerView mPlayer;
    private SimpleDraweeView imgSmallThumb;
    private TextView tvTitle;
    private TextView tvDescription;
    private XRefreshView xRefreshView;
    private RecyclerView rvList;
    private LinearLayout layFooter;
    private ImageView btBack;
    private ImageView btShare;
    private ImageView btLove;
    private LinearLayout layComment;
    private TextView tvComment;
    private LinearLayout layLike;
    private ImageView imgLike;
    private TextView tvLike;
    private RelativeLayout layLoading;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_radiodetail);
        ShareSDK.initSDK(this);
        user = ((MyApplication) getApplication()).getUser();
        Intent intent = getIntent();
        catId = intent.getIntExtra("catid", 0);
        initView();
        StatusBarUtil.setTranslucentForImageView(this, Config.STATUSBAR_ALPHA, null);
        page = 1;
        getList();
    }

    private void initView(){
        imgBg = getView(R.id.img_bg);
        mPlayer = getView(R.id.mPlayer);
        imgSmallThumb = getView(R.id.img_small_thumb);
        tvTitle = getView(R.id.tv_title);
        tvDescription = getView(R.id.tv_description);
        layFooter = getView(R.id.lay_footer);
        btBack = getView(R.id.bt_back);
        btShare = getView(R.id.bt_share);
        btLove = getView(R.id.bt_love);
        btLove.setVisibility(View.INVISIBLE);
        layComment = getView(R.id.lay_comment);
        tvComment = getView(R.id.tv_comment);
        layLike = getView(R.id.lay_like);
        imgLike = getView(R.id.img_like);
        tvLike = getView(R.id.tv_like);
        layLoading = getView(R.id.lay_loading);
        xRefreshView = getView(R.id.xRefreshView);
        rvList = getView(R.id.rv_list);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(OrientationHelper.VERTICAL);
        rvList.setLayoutManager(layoutManager);

        adapter = new RadioDetailAdapter(this);
        adapter.setOnItemClickListener(onItemClickListener);
        adapter.setCustomLoadMoreView(new XRefreshViewFooter(this));
        xRefreshView.setPullRefreshEnable(true);
        xRefreshView.setPullLoadEnable(true);
        xRefreshView.setMoveForHorizontal(true);
        xRefreshView.enableReleaseToLoadMore(true);
        xRefreshView.enableRecyclerViewPullUp(true);
        xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener(){
            @Override
            public void onRefresh() {
                super.onRefresh();
                page = 1;
                getList();
            }

            @Override
            public void onLoadMore(boolean isSilence) {
                super.onLoadMore(isSilence);
                page++;
                getList();
            }
        });
        rvList.setAdapter(adapter);

        layFooter.setOnClickListener(this);
        btBack.setOnClickListener(this);
        layComment.setOnClickListener(this);
        layLike.setOnClickListener(this);
        btShare.setOnClickListener(this);
    }

    private RadioDetailAdapter.OnItemClickListener onItemClickListener = new RadioDetailAdapter.OnItemClickListener() {
        @Override
        public void OnItemClickListener(View view, int position) {
            setData(list.get(position));
        }
    };

    private void setData(RadioBean bean) {
        imgSmallThumb.setImageURI(Uri.parse(bean.getThumb()));
//        imgThumb.setImageURI(Uri.parse(bean.getThumb()));
        tvTitle.setText(bean.getCatname());
        tvDescription.setText(getString(R.string.radio_playing) + bean.getTitle());
        if(firstLoad) {
            mPlayer.setData(data, false);
        }else {
            mPlayer.setData(data, true);
        }
        firstLoad = false;
        getContent();
    }

    private void initBottom() {
        tvComment.setText("" + data.getCommentnum());
        tvLike.setText("" + data.getLikenum());
        if (data.getLiked() == 1) {
            imgLike.setImageResource(R.drawable.bt_like_orange);
        }
    }

    private void getContent(){
        String url = Api.URL_RADIO + "?id=" + data.getId() + "&catid=" + catId;
        OkHttpUtils.get().url(url).tag(this).build().execute(new StringCallback() {

            @Override
            public void onBefore(Request request, int id) {
                super.onBefore(request, id);
                ligDialog = new LigDialog(RadioDetailActivity.this, getString(R.string.waiting));
                ligDialog.show();
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                ligDialog.dismiss();
            }

            @Override
            public void onResponse(String response, int id) {
                ligDialog.dismiss();
                data = JSONUtils.requestDetail(response, "data", RadioBean.class);
//                if (data != null) {
//                    setData(data);
//                }
                initBottom();
            }
        });
    }

    private void getList(){
        String url = Api.URL_RADIO_LIST + "?catid=" + catId + "&page=" + page;
        OkHttpUtils.get().url(url).tag(this).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                afterRequest();
            }

            @Override
            public void onResponse(String response, int id) {
                afterRequest();
                ArrayList<RadioBean> result = JSONUtils.requestList(response, "data", new TypeToken<ArrayList<RadioBean>>(){});
                if(page == 1){
                    if (result == null || result.size() == 0) {
                        Toast.makeText(RadioDetailActivity.this, R.string.list_empty, Toast.LENGTH_SHORT).show();
                    } else {
                        list = result;
                        if (firstLoad) {
                            data = list.get(0);
                            setData(data);
                        }
                        adapter.setData(list);
                        adapter.notifyDataSetChanged();
//                        mPlayer.setData(list.get(0),true);
                    }
                }else {
                    if (result == null || result.size() == 0) {
                        Toast.makeText(RadioDetailActivity.this, R.string.list_not_have, Toast.LENGTH_SHORT).show();
                    } else {
                        list.addAll(result);
                        adapter.setData(list);
                        adapter.notifyDataSetChanged();
                    }
                }
            }
        });
    }

    private void afterRequest() {
        layLoading.setVisibility(View.GONE);
        if (page == 1) {
            xRefreshView.stopRefresh();
        } else {
            xRefreshView.stopLoadMore();
        }
    }

    private void toComment() {
        Intent intent = new Intent(this, CommentActivity.class);
        intent.putExtra("articleid", data.getId());
        intent.putExtra("catid", data.getCatid());
        intent.putExtra("type", "video");
        startActivity(intent);
    }

    private void toShare() {
        if(data == null) return;
        Platform.ShareParams sp = new Platform.ShareParams();
        sp.setTitle(data.getTitle());
        sp.setTitleUrl(data.getShareurl());
        sp.setText(data.getDescription());
        sp.setSiteUrl(data.getShareurl());
        sp.setUrl(data.getShareurl());
        sp.setImageUrl(data.getThumb());
        sp.setSite(getString(R.string.app_name));
        ShareUtils.getInstance().setShareParams(this, sp).show();
    }

    void toLike() {
        if (user == null || user.getId() == 0) {
            Toast.makeText(this,R.string.not_login,Toast.LENGTH_SHORT).show();
            return;
        }
        if (data.getLiked() != 1) {
            addLike();
        } else {
            delLike();
        }
    }

    // 点赞
    private void addLike() {
        String url = Api.URL_ARTICLE_LIKE + "?id=" + data.getId() + "&catid=" + data.getCatid() + "&type=radio";
        String query = "id=" + data.getId() + "&catid=" + data.getCatid() + "&type=radio";
        OkHttpUtils
                .put()
                .url(url)
                .requestBody(query)
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(RadioDetailActivity.this, R.string.like_add_error, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        int status = 0;
                        status = JSONUtils.filterInt(response, "status", 0);
                        if (status == 1) {
                            Toast.makeText(RadioDetailActivity.this, R.string.like_add_success, Toast.LENGTH_SHORT).show();
                            imgLike.setImageResource(R.drawable.bt_like_orange);
                            int count = Integer.valueOf("" + tvLike.getText()) + 1;
                            tvLike.setText("" + count);
                            data.setLiked(1);
                        } else {
                            Toast.makeText(RadioDetailActivity.this, R.string.like_add_error, Toast.LENGTH_SHORT).show();
                        }
                    }
                });

    }

    // 取消点赞
    private void delLike() {
        String url = Api.URL_ARTICLE_LIKE + "?id=" + data.getId() + "&catid=" + data.getCatid() + "&type=radio";
        OkHttpUtils.delete().url(url).tag(this).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Toast.makeText(RadioDetailActivity.this, R.string.like_del_error, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String response, int id) {
                int status = 0;
                status = JSONUtils.filterInt(response, "status", 0);
                if (status == 1) {
                    Toast.makeText(RadioDetailActivity.this, R.string.like_del_success, Toast.LENGTH_SHORT).show();
                    imgLike.setImageResource(R.drawable.bt_like);
                    int count = Integer.valueOf("" + tvLike.getText()) - 1;
                    count = Math.max(0, count);
                    tvLike.setText("" + count);
                    data.setLiked(0);
                } else {
                    Toast.makeText(RadioDetailActivity.this, R.string.like_del_error, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.bt_back:
                finish();
                break;
            case R.id.lay_comment:
                toComment();
                break;
            case R.id.lay_like:
                toLike();
                break;
            case R.id.bt_share:
                toShare();
                break;
            default:
                break;
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPlayer.stop();
    }
}
